import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:synchronized/synchronized.dart';

class DatabaseUtils {
  static final DatabaseUtils shared = DatabaseUtils._internal();
  Database? _database; // 数据库实例
  final Lock _lock = Lock(); // 线程锁，确保数据库只初始化一次

  DatabaseUtils._internal(); // 私有构造函数（单例）

  /// **初始化 SQLite 数据库**
  Future<void> init() async {
    await _lock.synchronized(() async {
      _database ??= await _initDatabase();
    });
  }

  /// **获取数据库**
  Future<Database> get database async {
    if (_database == null) {
      throw Exception(
          'Database not initialized. Call `DatabaseUtils.shared.init()` first.');
    }
    return _database!;
  }

  /// **创建数据库**
  Future<Database> _initDatabase() async {
    final path = await getDatabasesPath();
    final dbPath = join(path, 'app_database.db');

    return await openDatabase(
      dbPath,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            age INTEGER NOT NULL
          )
        ''');
      },
    );
  }

  /// **插入用户**
  Future<int> insertUser(Map<String, dynamic> user) async {
    final db = await database;
    return await db.insert('users', user);
  }

  /// **获取所有用户**
  Future<List<Map<String, dynamic>>> getUsers() async {
    final db = await database;
    return await db.query('users');
  }

  /// **删除用户**
  Future<int> deleteUser(int id) async {
    final db = await database;
    return await db.delete('users', where: 'id = ?', whereArgs: [id]);
  }

  /// **关闭数据库**
  Future<void> close() async {
    final db = _database;
    if (db != null) {
      await db.close();
      _database = null;
    }
  }
}
